<!-- 短租对账 -->
<template>
  <div class="page-container">
    <date-summary :details="dataSummary" />

    <div class="tlts">
      <div class="tlt_l"></div>
      <div class="tlt_c">账单筛选</div>
    </div>
    <list-searcher :searchList="searchList" :needHide="true" v-model:searchForm="queryParam" @loadData="onSearchFn" @reset="onResize" />
    <div class="tlts">
      <div class="tlt_l"></div>
      <div class="tlt_c">订单筛选</div>
    </div>
    <list-searcher :searchList="orderSearchList" v-model:searchForm="queryParam" :showButton="false" ref="listSearcher2Ref" />
    <table-expense ref="expenseRef" :expenseOpts="table" @loadData="loadData" />

    <!-- 修改费用 -->
    <edit-cost-modal v-model="editCostModalVisible" :data="editCostModalData" @ok="loadData" />
    <!-- 查看对账明细 -->
    <view-bill-modal v-model="viewBillModalVisible" :data="viewBillModalData" @ok="loadData" />
    <!-- 查看结算明细 -->
    <view-settlement-modal v-model="viewSettlementModalVisible" :data="viewSettlementModalData" @ok="loadData" />
    <!-- 对账/批量对账 -->
    <batch-reconciliation-modal
      v-model="batchReconciliationModalVisible"
      :data="batchReconciliationModalData"
      @ok="handleBatchReconciliationOk"
    />
    <!-- 去结算弹窗 -->
    <shortOrderCostModal ref="sOrderCostRef" @close="loadData" />
    <!-- 添加对账备注 -->
    <add-reconciliation-remark ref="addReconciliationRemarkRef" @ok="loadData" />
    <!-- 操作记录 -->
    <operate-log-modal ref="opreatelogRef" />
    <!-- 导出 -->
    <export-model ref="exportRef" />
    <!-- 导入 -->
    <import-modal ref="imoportRef" action="/shortOrderBill/importExcel" download-import="shortOrderBill" @ok="loadData" />
    <EditCommissionModal ref="editCommissionModalRef" @ok="loadData" />
  </div>
</template>

<script setup name="examineShortOrderList" lang="ts">
  import DateSummary from './components/date-summary.vue'
  import EditCostModal from './modal/edit-cost-modal.vue'
  import ViewBillModal from './modal/view-bill-modal.vue'
  import ViewSettlementModal from './modal/view-settlement-modal.vue'
  import BatchReconciliationModal from './modal/batch-reconciliation-modal.vue'
  import shortOrderCostModal from './modal/short-order-cost-modal.vue'
  import addReconciliationRemark from './modal/addReconciliationRemark.vue'
  import operateLogModal from './modal/operate-log-modal.vue'
  import EditCommissionModal from './modal/edit-commission-modal.vue'
  import exportModel from './modal/export-model.vue'
  import { evalQueryParam } from '@/utils'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const routeQuery = route.query

  import { ref, reactive, onMounted, computed, h } from 'vue'
  import {
    getshortOrderBillList,
    getShortOrderBillSummary,
    revokeShortOrderBill,
    rejectShortOrderBill,
    downloadTemplate,
    getAllAccount,
    getShortOrderBillOverview,
    getShortOrderBillfeeNameList,
  } from '@/api/finance/examine'
  import { getWayByAccount } from '@/api/finance/turnover'
  import { useTable } from '@/hooks/table'
  import tableExpense from './components/table-expense.vue'
  import { usePageDict } from '@/hooks/useDict'
  import { Message, Modal } from '@arco-design/web-vue'
  import { download } from '@/utils/download'
  import dayjs from 'dayjs'

  // 获取费用名称列表
  const shortOrderBillFeeList = ref([])
  // 执行获取名称列表接口
  getShortOrderBillfeeNameList().then((res: any) => {
    shortOrderBillFeeList.value = res.result.map((item: any) => {
      return {
        label: item,
        value: item,
      }
    })
  })

  // 去结算
  const sOrderCostRef = ref()
  const shortOrderBillDict = usePageDict('shortOrderBillDict')
  const dict = usePageDict('turnoverDict')
  const shortOrderDict = usePageDict('shortOrderDict')
  const costConfirmDict = usePageDict('costConfirmDict')
  const dataSummary = ref<any>({ firstLine: {} })
  const editCostModalVisible = ref(false)
  const editCostModalData = ref({})
  const viewBillModalVisible = ref(false)
  const viewBillModalData = ref({})
  const viewSettlementModalVisible = ref(false)
  const viewSettlementModalData = ref({})
  const batchReconciliationModalVisible = ref(false)
  const batchReconciliationModalData = ref({})
  const addReconciliationRemarkRef = ref()
  const opreatelogRef = ref()
  const editCommissionModalRef = ref()
  const imoportRef = ref()
  const exportRef = ref()
  const expenseRef = ref()
  const queryParam = reactive<any>({
    endTimeBegin: dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00'),
    endTimeEnd: dayjs().subtract(-30, 'day').format('YYYY-MM-DD 23:59:59'),
    estimatedReturnTime: [
      dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00'),
      dayjs().subtract(-30, 'day').format('YYYY-MM-DD 23:59:59'),
    ],
  })
  const queryParamCopy = reactive<any>({})

  // 查询条件
  const oldIdList = ref(null)
  const searchList = computed(() => {
    return [
      {
        label: '费用名称',
        prop: 'itemNameList',
        type: 'a-select',
        options: shortOrderBillFeeList,
        multiple: true,
      },
      { label: '收支类型', prop: 'costType', type: 'a-select', options: shortOrderBillDict.costTypeEnum },
      { label: '对账状态', prop: 'billStatusList', type: 'a-select', options: shortOrderBillDict.feeBillStatusEnum, multiple: true },
      {
        label: '对账人',
        prop: 'billStaffIdList',
        type: 'remote-select',
        attrs: { type: 'staff_authOrg_multiple', params: { existSystem: 1, loginOrgId: 1 } },
      },
      {
        label: '对账日期',
        prop: 'billTimeRange',
        type: 'i-range-picker',
        attrs: {
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        change: (value = []) => {
          queryParam.billTimeBegin = value[0]
          queryParam.billTimeEnd = value[1]
        },
      },
      { label: '结算状态', prop: 'feeStatusList', type: 'a-select', options: shortOrderBillDict.orderFeeStatusEnum, multiple: true },
      {
        label: '结算日期',
        prop: 'settlementTimeRange',
        type: 'i-range-picker',
        attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
        change: (value = []) => {
          queryParam.settlementTimeBegin = value[0]
          queryParam.settlementTimeEnd = value[1]
        },
      },
      {
        label: '结算人',
        prop: 'settlementStaffIdList',
        type: 'remote-select',
        attrs: { type: 'staff_authOrg_multiple', params: { existSystem: 1, loginOrgId: 1 } },
      },
      {
        label: '结算方式',
        prop: 'payTypeList',
        type: 'a-select',
        options: wayByAccountList,
        attrs: {
          multiple: true,
        },
        change: (value: any[]) => {
          getAccountList(value)
        },
      },
      {
        label: '收付款账号',
        prop: 'payAccountIdList',
        type: 'a-select',
        disabled: !queryParam?.payTypeList || queryParam?.payTypeList?.length == 0,
        options: accountList,
        attrs: {
          multiple: true,
          placeholder: !queryParam?.payTypeList || queryParam?.payTypeList?.length == 0 ? '请先选择结算方式' : '请选择',
        },
      },
      {
        label: '费用生成日期',
        prop: 'costTimeRange',
        type: 'i-range-picker',
        attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
        change: (value = []) => {
          queryParam.feeCreateTimeBegin = value[0]
          queryParam.feeCreateTimeEnd = value[1]
        },
      },
      {
        label: '运营主体',
        prop: 'accountIdList',
        type: 'remote-select',
        attrs: { type: 'operate_subject_multiple' },
      },
      { label: '费用类型', prop: 'feeType', type: 'a-select', options: costConfirmDict.orderFeeTypeEnum },
      {
        label: '费项名称',
        prop: 'itemCategoryType',
        type: 'a-select',
        options: shortOrderBillDict.itemCategoryTypeEnum,
      },
    ]
  })

  // 预计还车时间
  const returnTime = ref([])
  // 实际还车时间
  const actualReturnTime = ref([])

  // searchGroup 下拉默认值
  const searchGroupPickUpTimeProp = ref('estimatedPickupTime')
  const searchGroupReturnTimeProp = ref('estimatedReturnTime')
  const orderSearchList = computed(() => {
    return [
      { label: '订单号', prop: 'orderCodeOrChannelCode', type: 'a-input' },
      { label: '订单状态', prop: 'orderStatusList', type: 'a-select', options: shortOrderBillDict.orderStatusEnum, multiple: true },
      { label: '车牌号', prop: 'carLicenseNoLike', type: 'a-input' },
      {
        label: '订单渠道',
        prop: 'channelTypes',
        type: 'a-select',
        options: dict.shortOrderChannelType,
        attrs: {
          multiple: true,
        },
      },
      {
        prop: searchGroupPickUpTimeProp.value,
        type: 'search-group',
        keepValueOnChange: true,
        childrens: [
          {
            label: '预取日期',
            prop: 'estimatedPickupTime',
            type: 'i-range-picker',
            attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
            change: (value = []) => {
              queryParam.actualStartTimeBegin = undefined
              queryParam.actualStartTimeEnd = undefined
              queryParam.estimatedPickupTime = value
              queryParam.actualPickupTime = value
              queryParam.startTimeBegin = value[0]
              queryParam.startTimeEnd = value[1]
              console.log('value', value)
            },
          },
          {
            label: '实取日期',
            prop: 'actualPickupTime',
            type: 'i-range-picker',
            attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
            change: (value = []) => {
              queryParam.startTimeBegin = undefined
              queryParam.startTimeEnd = undefined
              queryParam.estimatedPickupTime = value
              queryParam.actualPickupTime = value
              queryParam.actualStartTimeBegin = value[0]
              queryParam.actualStartTimeEnd = value[1]
              console.log('value', value)
            },
          },
        ],
      },
      {
        prop: searchGroupReturnTimeProp.value,
        type: 'search-group',
        keepValueOnChange: true,
        childrens: [
          {
            label: '预还日期',
            prop: 'estimatedReturnTime',
            type: 'i-range-picker',
            attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
            change: (value = []) => {
              queryParam.actualEndTimeBegin = undefined
              queryParam.actualEndTimeEnd = undefined
              queryParam.estimatedReturnTime = value
              queryParam.actualReturnTime = value
              queryParam.endTimeBegin = value[0]
              queryParam.endTimeEnd = value[1]
              console.log('value', value, queryParam)
            },
          },
          {
            label: '实还日期',
            prop: 'actualReturnTime',
            type: 'i-range-picker',
            attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
            change: (value = []) => {
              queryParam.endTimeBegin = undefined
              queryParam.endTimeEnd = undefined
              queryParam.estimatedReturnTime = value
              queryParam.actualReturnTime = value
              queryParam.actualEndTimeBegin = value[0]
              queryParam.actualEndTimeEnd = value[1]
              console.log('value', value, queryParam)
            },
          },
        ],
      },
      { label: '收付款客户名称', prop: 'customerNameLike', type: 'a-input' },
      {
        label: '取车门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
          params: {
            idList: oldIdList.value,
          },
        },
      },
      { label: '还车门店', prop: 'returnSiteIdList', type: 'remote-select', attrs: { type: 'site_lease_list_multiple' } },
      { label: '订单来源', prop: 'orderSource', type: 'a-select', options: shortOrderDict.orderSourceEnum },
      {
        label: '预计/实际取车时间',
        prop: 'orderStartOrActualTime',
        type: 'i-range-picker',
        attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
        change: (value = []) => {
          queryParam.orderStartOrActualTimeBegin = value[0]
          queryParam.orderStartOrActualTimeEnd = value[1]
          console.log('value', value, queryParam)
        },
      },
      {
        label: '预计/实际还车时间',
        prop: 'orderEndOrActualTime',
        type: 'i-range-picker',
        attrs: { valueFormat: 'YYYY-MM-DD HH:mm:ss', timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] } },
        change: (value = []) => {
          queryParam.orderEndOrActualTimeBegin = value[0]
          queryParam.orderEndOrActualTimeEnd = value[1]
          console.log('value', value, queryParam)
        },
      },
    ]
  })

  // table 配置
  const table = useTable({
    bordered: {
      wrapper: false,
      cell: true,
    },
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      { title: '费用名称', dataIndex: 'itemName', fixed: 'left', width: 100 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 100 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 100 },
      { title: '总额', dataIndex: 'amount', unit: '元', width: 100 },
      { title: '实结', dataIndex: 'payAmount', unit: '元', width: 100 },
      {
        title: '未结',
        dataIndex: 'waitPayAmount',
        unit: '元',
        headerCellClass: 'tableCommonRed',
        bodyCellClass: 'tableCommonRed',
        width: 100,
      },
      { title: '结算状态', dataIndex: 'feeStatusName', width: 100 },
      { title: '支付方式', slotName: 'payTypeNameList', width: 130 },
      { title: '结算人及时间', slotName: 'settlementInfo', width: 180 },
      { title: '已对账', dataIndex: 'billedAmount', unit: '元', width: 100 },
      {
        title: '未对账',
        dataIndex: 'waitBillAmount',
        unit: '元',
        width: 100,
        headerCellClass: 'tableCommonRed',
        bodyCellClass: 'tableCommonRed',
      },
      { title: '对账状态', dataIndex: 'billStatusName', width: 100 },
      { title: '对账人及时间', slotName: 'billInfo', width: 180 },
      { title: '费用备注', slotName: 'remark', width: 160, ellipsis: true },
      { title: '结算备注', slotName: 'settlementRemark', width: 160, ellipsis: true },
      { title: '对账备注', slotName: 'billRemark', width: 180, ellipsis: true },
      { title: '生成节点', dataIndex: 'createNodeName', width: 130 },
      { title: '费用生成时间', dataIndex: 'createTime', width: 180 },
    ],
    operates: [
      // 操作栏按钮
      // feeStatus 0 待结算 1 结算中 2 已结算 3 部分结算 9 无需结算
      // billStatus 1 待对账 2 部分对账 3 已对账 9 关闭对账
      {
        label: '对账',
        permission: 'svms:finance:examine:short-order.billConfirm',
        show: (row: any) => row.feeStatus != 9 && row.waitBillAmount > 0 && [1, 2].includes(row.billStatus),
        method: (row: any) => {
          batchReconciliationModalData.value = {
            id: row.id,
            title: '对账',
            operateType: 1,
          }
          batchReconciliationModalVisible.value = true
        },
      },
      {
        label: '撤销对账',
        permission: 'svms:finance:examine:short-order.billCancel',
        show: (record: any) => record.billStatus == 2 || record.billStatus == 3,
        method: (record: any) => {
          Modal.confirm({
            title: '撤销对账',
            content: () =>
              h('div', {}, [
                h('p', {}, `已对账总额：${record.billedAmount || 0}元，确认撤销吗？`),
                h('p', { style: 'color: red' }, '注：'),
                h('p', { style: 'color: red' }, '已对账的金额支持撤销'),
                h('p', { style: 'color: red' }, '撤销后支持操作驳回或重新对账'),
              ]),
            onOk: () => {
              revokeShortOrderBill({ id: record.id }).then((res: any) => {
                Message.success(res.message)
                loadData()
              })
            },
          })
        },
      },
      {
        // 实结=0不展示该按钮
        // 未对账=0时，不展示该按钮
        // 无需对账时不展示该按钮(关闭对账)
        label: '撤销结算',
        permission: 'svms:finance:examine:short-order.settlementReject',
        show: (record: any) => record.payAmount !== 0 && record.waitBillAmount !== 0 && record.billStatus != 9,
        method: (record: any) => {
          Modal.confirm({
            title: '撤销结算',
            content: () =>
              h('div', {}, [
                h('p', {}, `未对账总额：${record.waitBillAmount || 0}元，确认撤销结算吗？`),
                h('p', { style: 'color: red' }, '注：'),
                h('p', { style: 'color: red' }, '1.未对账的金额支持撤销结算，撤销后需重新结算'),
                h('p', { style: 'color: red' }, '2.支付方式为聚合支付的金额不支持撤销结算'),
                h('p', { style: 'color: red' }, '3.支付方式为押金抵扣且使用芝麻免押的不支持撤销结算'),
              ]),
            onOk: () => {
              rejectShortOrderBill({ idList: [record.id], operateType: 1 }).then((res: any) => {
                Message.success(res.message)
                loadData()
              })
            },
          })
        },
      },
      {
        label: '添加备注',
        permission: 'svms:finance:examine:short-order.billRemark',
        method: (record: any) => {
          addReconciliationRemarkRef.value.open(record)
        },
      },
    ],
    topButtons: [
      // 表格顶部栏按钮
      {
        label: '导入对账',
        permission: 'svms:finance:examine:short-order.billImport',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        label: '导出',
        permission: 'svms:finance:examine:short-order.billExport',
        method: () => {
          exportRef.value.open({ ...queryParam })
        },
      },
      {
        label: '批量撤销结算',
        permission: 'svms:finance:examine:short-order.batchRejection',
        method: () => {
          handleBatchReject()
        },
      },
      {
        type: 'primary',
        label: '批量对账',
        permission: 'svms:finance:examine:short-order.batchReconciliation',
        method: () => {
          // 获取选中的数据id expenseRef.value.getCheckListData()
          console.log('批量对账', expenseRef.value.getCheckListData())
          if (expenseRef.value.getCheckListData().length == 0) {
            Message.warning('无可对账的费项，请重新选择')
          } else {
            batchReconciliationModalData.value = {
              id: expenseRef.value.getCheckListData(),
              title: '批量对账',
              operateType: 2,
            }
            batchReconciliationModalVisible.value = true
          }
        },
      },
    ],
    orderButtons: [
      // 表格行内按钮
      {
        type: 'primary',
        label: '结算或修改总额',
        permission: 'svms:finance:examine:short-order.settleConfirm',
        // show: (record: any) => record.orderFeeDetailList.some((it: any) => it.waitPayAmount > 0 && it.feeStatus != 9),
        method: (record: any) => {
          sOrderCostRef.value.open(record)
        },
      },
      {
        type: 'primary',
        label: '修改费用',
        permission: 'svms:finance:examine:short-order.costEdit',
        method: (row: any) => {
          console.log('row', row)
          editCostModalData.value = {
            id: row.id,
            feeType: row.feeType,
            feeTypeName: row.feeTypeName,
            costType: row.costType,
            costTypeName: row.costTypeName,
            amount: row.amount,
            payAmount: row.payAmount,
            billedAmount: row.billedAmount,
            orderStatus: row.orderStatus,
          }
          editCostModalVisible.value = true
        },
      },
      {
        type: 'primary',
        label: '修改佣金及比例',
        permission: 'svms:finance:examine:short-order.editCommission',
        show: (record: any) => record.orderSource != 1,
        method: (record: any) => {
          editCommissionModalRef.value.open(record)
        },
      },
      {
        type: 'primary',
        label: '查看对账信息',
        permission: 'svms:finance:examine:short-order.billView',
        method: (row: any) => {
          console.log('row', row)
          viewBillModalData.value = {
            id: row.id,
          }
          viewBillModalVisible.value = true
        },
      },
      {
        type: 'primary',
        label: '查看结算明细',
        permission: 'svms:finance:examine:short-order.settlementView',
        method: (row: any) => {
          console.log('row', row)
          viewSettlementModalData.value = {
            id: row.id,
          }
          viewSettlementModalVisible.value = true
        },
      },
      {
        type: 'primary',
        label: '操作记录',
        permission: 'svms:finance:examine:short-order.recordView',
        method: (record: any) => {
          opreatelogRef.value.open(record)
        },
      },
    ],
  })

  // 先定义类型
  type TimeSearchGroupKeys = keyof typeof timeSeachGroup
  const timeSeachGroup = {
    estimatedPickupTime: ['startTimeBegin', 'startTimeEnd'],
    estimatedReturnTime: ['endTimeBegin', 'endTimeEnd'],
    actualPickupTime: ['actualStartTimeBegin', 'actualStartTimeEnd'],
    actualReturnTime: ['actualEndTimeBegin', 'actualEndTimeEnd'],
    orderStartOrActualTime: ['orderStartOrActualTimeBegin', 'orderStartOrActualTimeEnd'],
    orderEndOrActualTime: ['orderEndOrActualTimeBegin', 'orderEndOrActualTimeEnd'],
  }

  // 数据总览
  let prevOrderBillParam: any = null
  // 获取订单查询条件参数
  const buildShortOrderBillOverviewParam = () => {
    const param = {} as Record<string, any>
    orderSearchList.value.forEach((item: any) => {
      const { type, prop } = item
      if (type == 'search-group' || type == 'i-range-picker') {
        const childProps = timeSeachGroup[prop as TimeSearchGroupKeys]
        if (childProps) {
          param[childProps[0]] = queryParam[childProps[0]]
          param[childProps[1]] = queryParam[childProps[1]]
        }
      } else {
        param[prop] = queryParam[prop]
      }
    })
    return param
  }
  /**
   * 顶部数据总览
   * 当订单查询条件变化时，重新请求数据总览数据
   */
  const getDataOverview = () => {
    // 构造订单查询条件
    const param = buildShortOrderBillOverviewParam()
    if (!prevOrderBillParam || JSON.stringify(prevOrderBillParam) !== JSON.stringify(param)) {
      prevOrderBillParam = param
      getShortOrderBillOverview(param).then((res: any) => {
        dataSummary.value.firstLine = {
          orderTotalAmount: res.result.orderTotalAmount,
          otaStatementTotalAmount: res.result.otaStatementTotalAmount,
          commissionAmountTotal: res.result.commissionAmountTotal,
          orderRevenueAmountTotal: res.result.orderRevenueAmountTotal,
          statementTotalAmount: res.result.statementTotalAmount,
          waitStatementTotalAmount: res.result.waitStatementTotalAmount,
        }
      })
    }
  }

  /**
   * 获取数据汇总
   */
  const getSummary = () => {
    getShortOrderBillSummary(queryParam).then((res: any) => {
      dataSummary.value = { ...res.result, firstLine: dataSummary.value.firstLine }
    })
  }

  // 存储所有数据
  const allPageData = reactive(new Map())
  // 获取所有数据方法
  const getAllPageData = computed(() => Array.from(allPageData.values()).flat())
  // 将分页重置
  table.pagination.pageSizes = [10, 20, 30]
  const loadData = (pageNumber?: number) => {
    table.tableLoading = true
    if (pageNumber) {
      queryParam.pageNumber = pageNumber
      table.pagination.page = pageNumber
    } else {
      queryParam.pageNumber = table.pagination.page || 1
      queryParam.pageSize = table.pagination.pageSize
    }

    // feeStatus 0 待结算 1 结算中 2 已结算 3 部分结算 9 无需结算
    // 如果搜索条件为空 将之前的搜索条件赋值给queryParam
    let isEmptyStatus = isQueryParmEmpty()
    if (isEmptyStatus) Object.assign(queryParam, queryParamCopy)
    getshortOrderBillList(queryParam)
      .then((res: any) => {
        const result = res.result.data
        result.forEach((element: any) => {
          element.orderFeeDetailList.forEach((item: any) => {
            item.disabled = !([1, 2].includes(item.billStatus) && item.waitBillAmount > 0 && item.feeStatus != 9)
          })
        })
        table.dataList = result
        table.pagination.pageCount = res.result.total
        allPageData.set(table.pagination.page, result)
      })
      .finally(() => {
        table.tableLoading = false
      })

    getSummary()
    getDataOverview()
  }
  const isEmpty = (obj) => {
    return obj === '' || obj === undefined || obj === null || (Array.isArray(obj) && obj.length === 0)
  }
  // 判断搜索条件是否为空
  const isQueryParmEmpty = () => {
    let isSearchEmpty = []
    for (const key in queryParam) {
      if (!['pageNumber', 'pageSize'].includes(key)) {
        isSearchEmpty.push(isEmpty(queryParam[key]))
      }
    }
    return isSearchEmpty.every((it) => !!it)
  }
  const onSearchFn = () => {
    // 如果搜索条件为空，进行查询拦截
    let isEmptyStatus = isQueryParmEmpty()
    if (isEmptyStatus) return Message.warning('为保证加载速度，请至少筛选一个信息')
    // 将复选框清空
    expenseRef.value.updateCheckStatusFn(false)
    loadData()
    // 搜索后将搜索条件赋值给queryParamCopy
    Object.assign(queryParamCopy, queryParam)
  }
  const handleBatchReconciliationOk = () => {
    // 将复选框清空
    expenseRef.value.updateCheckStatusFn(false)
    loadData()
  }

  const listSearcher2Ref = ref()
  const onResize = () => {
    expenseRef.value.updateCheckStatusFn(false)
    // 重置搜索组
    listSearcher2Ref.value.resetSearchGroup()

    Object.keys(queryParam).forEach((key) => {
      queryParam[key] = undefined

      if (key == 'pageNumber') {
        queryParam[key] = 1
      }
      if (key == 'pageSize') {
        queryParam[key] = 10
      }
      if (key == 'endTimeBegin') {
        queryParam[key] = dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00')
      }
      if (key == 'endTimeEnd') {
        queryParam[key] = dayjs().subtract(-30, 'day').format('YYYY-MM-DD 23:59:59')
      }
      if (['estimatedReturnTime', 'actualReturnTime'].includes(key)) {
        queryParam['estimatedReturnTime'] = [
          dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00'),
          dayjs().subtract(-30, 'day').format('YYYY-MM-DD 23:59:59'),
        ]
        queryParam['actualReturnTime'] = [
          dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00'),
          dayjs().subtract(-30, 'day').format('YYYY-MM-DD 23:59:59'),
        ]
      }
    })
  }

  // 结算方式
  const wayByAccountList = ref([])
  const getwayByAccountList = (account?: any) => {
    getWayByAccount({
      accountList: account || [],
    }).then((res: any) => {
      wayByAccountList.value = res.result.map((item: any) => {
        return {
          label: item.name,
          value: item.value,
        }
      })
    })
  }

  // 收付款账号
  const accountList = ref([])
  const getAccountList = (value: any[]) => {
    if (value && value.length == 0) {
      queryParam.payAccountIdList = []
      accountList.value = []
      return
    }

    getAllAccount({
      ways: value || [],
    }).then((res: any) => {
      res.result.forEach((item: any) => {
        item.label = `${item.account}-${item.bank}`
        item.value = item.id
      })
      accountList.value = res.result
    })
  }

  // 批量驳回
  const handleBatchReject = () => {
    // 如选择的费项中有不支持驳回的费项，点击批量驳回时，
    // 仅展示支持驳回的费项信息，如都不符合，则点击批量驳回时，提示商户：无可驳回的费项，请重新选择
    if (expenseRef.value.getCheckListData().length) {
      // 筛选出包含 expenseRef.value.getCheckListData() 的数据
      const filteredData = getAllPageData.value.flatMap((item: any) =>
        item.orderFeeDetailList.filter((detail: any) => expenseRef.value.getCheckListData().includes(detail.id))
      )
      console.log('filteredData', filteredData)
      // 已结算未对账的金额金额支持驳回
      const filteredArray = filteredData.filter(
        (item: any) => item.payAmount !== 0 && item.waitBillAmount !== 0 && item.billStatus != 9 && item.payType != 4
      )
      console.log('filteredArray', filteredArray)
      if (filteredArray.length) {
        Modal.confirm({
          title: '批量撤销结算',
          content: () =>
            h('div', {}, [
              h(
                'p',
                {},
                `您选择了${expenseRef.value.getCheckListData().length}笔费项，其中${filteredArray.length}笔费项支持撤销，确认撤销结算嘛？`
              ),
              h('p', { style: 'color: red' }, '注：'),
              h('p', { style: 'color: red' }, '1.未对账的金额支持撤销结算，撤销后需重新结算'),
              h('p', { style: 'color: red' }, '2.支付方式为聚合支付的金额不支持撤销结算'),
              h('p', { style: 'color: red' }, '3.支付方式为押金抵扣且使用芝麻免押的不支持撤销结算'),
            ]),
          onOk: () => {
            rejectShortOrderBill({ idList: filteredArray.map((item: { id: any }) => item.id), operateType: 2 }).then(() => {
              Message.success('驳回成功')
              expenseRef.value.updateCheckStatusFn(false)
              loadData()
            })
          },
        })
      } else {
        Message.warning('无可撤销结算的费项，请重新选择')
      }
    } else {
      Message.warning('请先勾选需要确认的数据！')
    }
  }

  const importHandle = () => {
    downloadTemplate().then((res: any) => {
      download(res, 'application/excel;charset=UTF-8', '短租对账模板.xlsx')
    })
  }

  onMounted(() => {
    // 取车门店
    if (routeQuery.siteIdList) {
      let siteIdList = evalQueryParam(routeQuery.siteIdList)
      siteIdList = siteIdList.map((item) => String(item))
      queryParam.siteIdList = siteIdList
      oldIdList.value = siteIdList
    }
    // 对账状态
    if (routeQuery.billStatusList) {
      let billStatusList = evalQueryParam(routeQuery.billStatusList)
      queryParam.billStatusList = billStatusList
    }
    // 费用名称
    if (routeQuery.itemNameList) {
      let itemNameList = evalQueryParam(routeQuery.itemNameList)
      queryParam.itemNameList = itemNameList
    }
    // 订单渠道
    if (routeQuery.channelTypes) {
      let channelTypes = evalQueryParam(routeQuery.channelTypes)
      queryParam.channelTypes = channelTypes
    }
    // 费用类型
    if (routeQuery.feeType) {
      let feeType = evalQueryParam(routeQuery.feeType)
      queryParam.feeType = feeType
    }
    // 结算状态
    if (routeQuery.feeStatusList) {
      let feeStatusList = evalQueryParam(routeQuery.feeStatusList)
      queryParam.feeStatusList = feeStatusList
    }
    // 订单状态
    if (routeQuery.orderStatusList) {
      let orderStatusList = evalQueryParam(routeQuery.orderStatusList)
      queryParam.orderStatusList = orderStatusList
    }
    // 费项名称
    if (routeQuery.itemCategoryType) {
      let itemCategoryType = evalQueryParam(routeQuery.itemCategoryType)
      queryParam.itemCategoryType = itemCategoryType
    }
    // 时间
    if (routeQuery.orderTimeQueryType && routeQuery.startTime && routeQuery.endTime) {
      const orderTimeQueryType = routeQuery.orderTimeQueryType
      const startTime = dayjs(routeQuery.startTime).format('YYYY-MM-DD 00:00:00')
      const endTime = dayjs(routeQuery.endTime).format('YYYY-MM-DD 23:59:59')

      // 清空默认时间筛选
      queryParam.endTimeBegin = undefined
      queryParam.endTimeEnd = undefined
      queryParam.estimatedReturnTime = undefined

      const timeQueryMap = {
        // 预计或实际取车时间
        '1': { prop: 'orderStartOrActualTime', begin: 'orderStartOrActualTimeBegin', end: 'orderStartOrActualTimeEnd' },
        // 预计取车时间
        '2': { prop: 'estimatedPickupTime', begin: 'startTimeBegin', end: 'startTimeEnd', searchGroupProp: 'estimatedPickupTime' },
        // 实际取车时间
        '3': { prop: 'actualPickupTime', begin: 'actualStartTimeBegin', end: 'actualStartTimeEnd', searchGroupProp: 'actualPickupTime' },
        // 预计或实际还车时间
        '4': { prop: 'orderEndOrActualTime', begin: 'orderEndOrActualTimeBegin', end: 'orderEndOrActualTimeEnd' },
        // 预计还车时间
        '5': { prop: 'estimatedReturnTime', begin: 'endTimeBegin', end: 'endTimeEnd', searchGroupProp: 'estimatedReturnTime' },
        // 实际还车时间
        '6': { prop: 'actualReturnTime', begin: 'actualEndTimeBegin', end: 'actualEndTimeEnd', searchGroupProp: 'actualReturnTime' },
      }

      const timeQuery = timeQueryMap[orderTimeQueryType]
      if (timeQuery) {
        queryParam[timeQuery.prop] = [startTime, endTime]
        queryParam[timeQuery.begin] = startTime
        queryParam[timeQuery.end] = endTime
        // searchGroupProp
        if (['estimatedPickupTime', 'actualPickupTime'].includes(timeQuery.searchGroupProp)) {
          searchGroupPickUpTimeProp.value = timeQuery.searchGroupProp
        }
        if (['estimatedReturnTime', 'actualReturnTime'].includes(timeQuery.searchGroupProp)) {
          searchGroupReturnTimeProp.value = timeQuery.searchGroupProp
        }
      }
    }
    // 保单开始时间
    if (routeQuery.startTime && routeQuery.endTime) {
      let startTime = routeQuery.startTime
      let endTime = routeQuery.endTime
      queryParam.startDateStart = startTime
      queryParam.startDateEnd = endTime
      queryParam.startDate = [startTime, endTime]
      queryParam.endDateStart = startTime
      queryParam.endDateEnd = endTime
      queryParam.endDate = [startTime, endTime]
    }

    getDataOverview()
    loadData()
    getwayByAccountList()
  })
</script>

<style lang="less" scoped>
  .tableCommonRed {
    .arco-table-th-title,
    .arco-table-td-content {
      color: #f53f3f !important;
    }
  }

  .tlts {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
    .tlt_l {
      width: 4px;
      height: 18px;
      background: #1890ff;
    }
    .tlt_c {
      margin: 0 8px;
      color: #1d2129;
      font-weight: 500;
      font-size: 16px;
    }
  }
</style>
